<template>
  <div class="user-reg-layout  home-main-box">

    <div class="user-reg-form form">
      <!-- 邮箱注册开始 -->
      <template>
        <el-form ref="emailForm" key="emailForm" :rules="emailRules" :model="emailFrom">

          <el-form-item key="userEmail" prop="user_email" style="width: 100%;">
            <el-input key="userEmail_input" v-model.trim="emailFrom.user_email" type="text" placeholder="请输入您的邮箱" />
          </el-form-item>

          <div class="code-box">
            <el-form-item key="emailCode" prop="code">
              <el-input
                key="emailCode_input"
                v-model.trim="emailFrom.code"
                placeholder="邮箱验证码"
                maxlength="6"
                autocomplete="off"
              />

            </el-form-item>

            <el-form-item key="emailCode1" prop="code" style="position: fixed;z-index: -99;bottom: -9999px;opacity: 0;">
              <el-input key="emailCode1_input" placeholder="邮箱验证码" maxlength="6" style="position: fixed;z-index: -99;bottom: -9999px;opacity: 0;" />
            </el-form-item>

            <el-button size="small" class="msg-btn" type="primary" @click="subPhoneEmailCode('emailForm')">{{ codeText }}</el-button>

          </div>

          <el-form-item key="emailPwd" prop="pwd" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;">
            <pwdInput key="emailPwd_input" placeholder="请输入您的密码" autocomplete="off" style="position: fixed;bottom: -9999px;opacity: 0;z-index: -99;"></pwdInput>
          </el-form-item>

          <el-form-item key="emailPwd" prop="pwd">

            <pwdInput key="emailPwd_input" v-model.trim="emailFrom.pwd" placeholder="请输入您的密码" autocomplete="off"></pwdInput>
          </el-form-item>

          <el-form-item key="emailPwd2" prop="pwd2">
            <pwdInput key="emailPwd2_input" v-model.trim="emailFrom.pwd2" placeholder="请再次输入您的密码" @keyup.native.enter="submitRegister('emailForm')"></pwdInput>
          </el-form-item>

          <div v-if="false" class="code-box">
            <el-form-item prop="age">
              <el-input placeholder="请输入验证码" />
            </el-form-item>

            <img v-if="code" :src="code" class="code-img">

          </div>

          <div class="pwd-box" style="justify-content: flex-start;">
            <el-checkbox v-model="agreeWith">
              <span style="font-size: 12px;color:#39444E">已阅读并同意</span>
            </el-checkbox>
            <p style="font-size: 12px;"><em style="font-size: 12px;" class="pointer" @click.stop="intoClause ('employ')">《3YData平台用户使用协议》</em>和<em
              style="font-size: 12px;"
              class="pointer"
              @click.stop="intoClause('privacy')"
            >《隐私政策》</em></p>

          </div>

          <div class="reg-btn-list">
            <el-button
              v-loading="emailLoading"
              type="success"
              size="small"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              @click="submitRegister('emailForm')"
            >注册</el-button>
            <span @click="goLogin">使用已有账户登录</span>
          </div>

        </el-form>
      </template>
      <!-- 邮箱注册结束 -->
    </div>
  </div>
</template>
<script>
import {
  userCode, // 验证图片验证码是否正确；
  createCode,
  emailRegister, // 邮箱验证码获取
  smsRegister, // 手机验证码获取
  register,
  findCampaignCount
} from '@/api/user.js'
  // type: 'register' // 注册字段
  // type: 'retrieve' ,// 找回字段
  // type:'modifyEmail'//更换字段
import {
  isValidPhone,
  isValidEmail,
  isValidCode
} from '@/utils/validate'

import {
  getDefultPath
} from '@/utils/index.js'

export default {
  data() {
    // 手机密码一致验证
    var validatePhonePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.phoneFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    // 邮箱密码一致验证
    var validateMailPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.emailFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      codeTime: undefined, // 定时器
      phoneLoading: false,
      emailLoading: false,
      account: '',
      password: '',
      type: 'email',
      code: undefined, // 验证码图片路径
      codeText: '获取验证码', // 验证码按钮文字
      countDown: 0, // 倒计时秒数
      agreeWith: false,
      phoneFrom: {
        user_phone: '',
        SMS: '',
        pwd2: '',
        pwd: '',
        code: ''
      },
      phoneRules: {
        user_phone: [{
          required: true,
          message: '请输入您的手机号码',
          trigger: 'blur'
        },
        {
          validator: isValidPhone,
          trigger: 'blur'
        }
        ],
        SMS: [{
          required: true,
          message: '请输入您的验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        pwd2: [{
          required: true,
          validator: validatePhonePass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ],
        code: [{
          validator: isValidCode,
          trigger: 'blur'
        }]
      },
      emailFrom: {
        user_email: '',
        pwd: '',
        pwd2: '',
        code: ''
      },
      emailRules: {
        user_email: [{
          required: true,
          message: '请输入您的邮箱',
          trigger: 'blur'
        },
        {
          validator: isValidEmail,
          trigger: 'blur'
        }
        ],
        code: [{
          required: true,
          message: '请输入邮箱验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }

        ],
        pwd2: [{
          required: true,
          validator: validateMailPass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ]
      }
    }
  },
  mounted() {
    this.phoneFrom = {}
    this.emailFrom = {}
    // this.createCode()
  },

  beforeDestroy() {
    if (this.codeTime) {
      return clearInterval(this.codeTime)
    }
  },
  methods: {
    handleInput(e) {
      this.$forceUpdate()
    },
    intoClause(type) {
      const routeUrl = this.$router.resolve({
        path: '/account',
        query: {
          type
        }
      })
      window.open(routeUrl.href, '_blank')
    },

    // 获取验图片证码
    async createCode() {
      const res = await createCode()
      const blob = new Blob([res.data], {
        type: 'image/png'
      })
      const url = window.URL.createObjectURL(blob)
      this.code = url
    },

    // 发送手机或者邮箱验证码
    subPhoneEmailCode(type) {
      if (this.countDown > 0) return false

      if (type === 'phoneForm') {
        // 如果是请求发送手机验证码
        var MobileRegex = /^1[0-9]{10}$/
        const value = this.phoneFrom.user_phone
        if (!MobileRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的手机号码!')
        } else {
          this.getPhoneCode()
        }
        // 手机验证结束
      } else {
        // 如果是邮箱
        var mailRegex = /^\w*@[-a-zA-Z0-9]{1,20}\.[0-9a-z]{2,3}$/
        const value = this.emailFrom.user_email
        if (!mailRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的邮箱!')
        } else {
          this.getEmailCode()
        }
      }
    },

    // 邮箱验证码获取
    async getEmailCode() {
      const obj = {
        account: this.emailFrom.user_email,
        type: 'register' // 注册字段
      }
      const {
        data
      } = await emailRegister(obj)
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
        // this.createCode()
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },
    // 手机验证码获取
    async getPhoneCode() {
      const obj = {
        account: this.phoneFrom.user_phone,
        type: 'register' // 注册字段
      }
      const {
        data
      } = await smsRegister({ ...obj
      })
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },

    // 验证码倒计时
    runTime() {
      const that = this
      this.countDown = 60
      this.codeText = this.countDown + 's'
      this.codeTime = setInterval(() => {
        if (that.countDown <= 1) {
          clearInterval(this.codeTime)
          that.countDown = 0
          this.codeText = '获取验证码'
        } else {
          that.countDown -= 1
          this.codeText = this.countDown + 's'
        }
      }, 1000)
    },
    // 验证图片验证码是否正确
    async codeIsTrue(type) {
      const code = this.phoneFrom.code
      if (code < 4) {
        this.$message.closeAll()
        return false
      } else {
        const {
          data
        } = await userCode(code)
        if (data.code !== 20000) {
          this.$message.closeAll()
          this.$message.error(data.message || '验证码错误')
          /* this.createCode() */
          return false
        } else {
          return true
        }
      }
    },

    // 提交注册
    submitRegister(form) {
      const windowWidth = document.body.clientWidth
      if (windowWidth < 900) {
        this.$message.closeAll()
        this.$message.error('请在PC端提交')
        return false
      }
      this.phoneLoading = true
      this.emailLoading = true

      this.$refs[form].validate(async(valid) => {
        if (valid) {
          if (!this.agreeWith) {
            this.$message.closeAll()
            this.$message.error('请阅读并同意协议和政策')
            this.phoneLoading = false
            this.emailLoading = false
            return false
          }
          let data = {}
          if (form.indexOf('phone') !== -1) {
            // const flag = await this.codeIsTrue()
            // if (!flag) return false
            this.account = this.phoneFrom.user_phone
            this.password = this.phoneFrom.pwd
            data = {
              mobile: this.phoneFrom.user_phone,
              pwd: this.phoneFrom.pwd,
              code: this.phoneFrom.SMS
            }
          } else {
            this.account = this.emailFrom.user_email
            this.password = this.emailFrom.pwd
            data = {
              email: this.emailFrom.user_email,
              pwd: this.emailFrom.pwd,
              code: this.emailFrom.code
            }
          }
          const res = await register({ ...data
          })
          this.phoneLoading = false
          this.emailLoading = false
          if (res.data.code !== 20000) {
            // 证明注册失败了
            this.$message.closeAll()
            this.$message.error(res.data.message || '注册失败，请稍后重试')
            /* this.createCode() */
          } else {
            this.$message.closeAll()
            this.$message({
              message: '注册成功，即将登录',
              type: 'success'
            })
            this.userLogin()
          }
        } else {
          this.phoneLoading = false
          this.emailLoading = false
          // console.log('表单验证失败')
        }
      })
    },
    // 登录
    async userLogin() {
      let formlist = {}
      if (this.account.indexOf('@') !== -1) {
        formlist = {
          email: this.account,
          pwd: this.password
        }
      } else {
        formlist = {
          mobile: this.account,
          pwd: this.password
        }
      }
      const res = await this.$store.dispatch('user/login', formlist)
      const {
        data
      } = res

      if (data.code === 20000) {
        const userInfo = await this.$store.dispatch('user/getInfo')
        const path = getDefultPath(userInfo.roleName)
        this.$router.replace({
          path
        })
      } else {
        this.$message.error(data.message || '登录失败，请稍后重试')
      }
    },

    /*    async isFirstLogin() {
                              const res = await findCampaignCount(this.$store.state.user.unit)
                              this.$message.closeAll()
                              this.$message({
                                message: '登录成功，即将跳转页面',
                                type: 'success'
                              })

                              if (res.data.data > 0) {
                                this.$router.replace({
                                  path: '/'
                                })
                              } else {
                                this.$router.replace({
                                  path: '/'
                                })
                              }
                              // showWindowMessage(4, res.data.message)
                              // this.setCookie(this.form.user, this.form.pwd, 7)
                            }, */
    // 改变注册形式
    /* changeRegType() {
        // 清除定时器
        if (codeTime) {
          clearInterval(codeTime)
        }
        // 重置发送验证码按钮字段
        this.countDown = 0
        this.codeText = '获取验证码'
        // 同意协议重置
        this.agreeWith = false
        if (this.type === 'phone') {
          this.$refs['phoneForm'].resetFields()
          this.$nextTick(function() {
            this.type = 'email'
            this.$forceUpdate()
          })
        } else {
          this.$refs['emailForm'].resetFields()
          this.$nextTick(function() {
            this.type = 'phone'
            this.$forceUpdate()
          })
        }
      }, */
    // 去登录页面
    goLogin() {
      if (this.type == 'phone') {
        this.$refs['phoneForm'].resetFields()
      } else {
        this.$refs['emailForm'].resetFields()
      }
      this.$nextTick(function() {
        this.$emit('changeType', 'login')
      })
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import './style/form.scss';

  .type-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0.32rem;
    line-height: 0.46rem;
    font-size: 0.24rem;

    .blue-btn {
      width: 48%;
    }

  }
</style>
